package com.ivm.hibernate.dao;

import com.ivm.domain.WorkoutType;
import com.ivm.hibernate.HibernateUtil;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Ivana
 */
public class WorkoutTypeDao {
    
     public WorkoutType save(WorkoutType workoutType) {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        Long objectId = (Long) session.save(workoutType);
        workoutType.setId(objectId);

        session.getTransaction().commit();
        session.close();

        return workoutType;
    }

    public WorkoutType update(WorkoutType workoutType){
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        session.merge(workoutType);

        session.getTransaction().commit();
        session.close();

        return workoutType;
    }

    public WorkoutType delete(WorkoutType workoutType){
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        session.delete(workoutType);

        session.getTransaction().commit();
        session.close();

        return workoutType;
    }

    public List getAll() {
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();

        List<WorkoutType> workoutTypes = session.createQuery("from WorkoutType").list();

        session.close();

        return  workoutTypes;
    }

    public WorkoutType findById(Long id){
        SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
        Session session = sessionFactory.openSession();

        WorkoutType workoutType = (WorkoutType) session.get(WorkoutType.class, id);

        session.close();

        return workoutType;
    }
}
